package zhan.controller;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import zhan.annotation.RzAnnotation;
import zhan.entity.User;
import zhan.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    public static final Logger log = Logger.getLogger(UserController.class);
    /**
     *
     */
    @Autowired
    private UserService userService;

    @RzAnnotation(cznr = "get登录请求")
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String index() {
        log.info("------------------------>测试启动准备进入login 页面");
        return "login";
    }

    @RzAnnotation(cznr = "post登录请求")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpServletRequest request, Model model){

        //如果登陆失败，则从shiro中获取异常信息 shiroLoginFailure 是shiro的异常类的全限定名
        String exceptionClassName = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);

        if (exceptionClassName != null) {
            //根据shiro返回的异常类路径，抛出指定的一异常信息
            if (UnknownAccountException.class.getName().equals(exceptionClassName)){
                model.addAttribute("msg", "账号不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                model.addAttribute("msg","登录密码错误");
            }else {
                model.addAttribute("msg", "其他异常信息");
            }
        }
//        log.error("-------------------->登录控制器");
//        String userName = request.getParameter("login_name");
//        String pwd = request.getParameter("login_pwd");
//        String msg;
//        UsernamePasswordToken token = new UsernamePasswordToken(userName, pwd);
//        try {
//            /**
//             * 此处subject没有被认证
//             */
//            Subject subject = SecurityUtils.getSubject();
//            subject.login(token);
//            log.info("认证成功");
//            if (subject.isAuthenticated()) {
//                return "redirect:list";
//            } else {
//                return "login";
//            }
//        } catch (UnknownAccountException e) {
//            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (IncorrectCredentialsException e) {
//            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (ExcessiveAttemptsException e) {
//            msg = "登录失败次数过多";
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (LockedAccountException e) {
//            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (DisabledAccountException e) {
//            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (ExpiredCredentialsException e) {
//            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        } catch (UnauthorizedException e) {
//            msg = "您没有得到相应的授权！" + e.getMessage();
//            model.addAttribute("message", msg);
//            System.out.println(msg);
//        }
        return "login";
    }

    @RequestMapping("/loginOut")
    public String loginOut(){
        SecurityUtils.getSubject().logout();
        return "redirect:login";
    }

    @RzAnnotation(cznr = "测试自定义注解")
    @RequestMapping("/list")
    public String userList(Model model) {
        log.info("---------即将进入拦截器-----------------");
        List<User> users = userService.selectAllUser();
        model.addAttribute("list", users);
        return "userList";
    }

    @RequestMapping("/edit")
    public String edit(int id, Model model) {
        User user = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user);
        return "edit";
    }

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(User user) {
        userService.editUser(user);
        return "redirect:list"; //重定向到list.jsp页面
    }

    @RequestMapping("/delete")
    public String deleteById(int id) {
        userService.deleteUser(id);
        return "redirect:list";
    }

    @RequestMapping("/toadd")
    public String toAddUser() {
        return "add";
    }

    @RequestMapping("/add")
    public String addUser(User user) {
        userService.save(user);
        return "redirect:list";
    }

}
